<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="订单号与抢购表一致" path="orderSn">
          <n-input placeholder="请输入订单号与抢购表一致" v-model:value="formParams.orderSn" />
        </n-form-item>
        <n-form-item label="活动场次id" path="rushPurchaseId">
          <n-input placeholder="请输入活动场次id" v-model:value="formParams.rushPurchaseId" />
        </n-form-item>
        <n-form-item label="抢购活动明细id" path="rushPurchaseDetailId">
          <n-input placeholder="请输入抢购活动明细id" v-model:value="formParams.rushPurchaseDetailId" />
        </n-form-item>
        <n-form-item label="上架后，下一场抢购活动明细id" path="nextRushPurchaseDetailId">
          <n-input placeholder="请输入上架后，下一场抢购活动明细id" v-model:value="formParams.nextRushPurchaseDetailId" />
        </n-form-item>
        <n-form-item label="原价（购买价）" path="originalPrice">
          <n-input placeholder="请输入原价（购买价）" v-model:value="formParams.originalPrice" />
        </n-form-item>
        <n-form-item label="上架后新价格" path="newPrice">
          <n-input placeholder="请输入上架后新价格" v-model:value="formParams.newPrice" />
        </n-form-item>
        <n-form-item label="服务费（上架费）" path="servicePrice">
          <n-input placeholder="请输入服务费（上架费）" v-model:value="formParams.servicePrice" />
        </n-form-item>
        <n-form-item label="第三方支付单号" path="paymentOrderNo">
          <n-input placeholder="请输入第三方支付单号" v-model:value="formParams.paymentOrderNo" />
        </n-form-item>
        <n-form-item label="上架会员id" path="memberId">
          <n-input placeholder="请输入上架会员id" v-model:value="formParams.memberId" />
        </n-form-item>
        <n-form-item label="状态0默认1支付成功" path="status">
          <n-input placeholder="请输入状态0默认1支付成功" v-model:value="formParams.status" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getPutSaleOrderPage, savePutSaleOrder, updatePutSaleOrder, deletePutSaleOrder } from '@/api/promotion/putSaleOrder';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { ResultEnum } from '@/enums/httpEnum';

  const rules = {
    orderSn: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入订单号与抢购表一致',
    },
    rushPurchaseId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入活动场次id',
    },
    rushPurchaseDetailId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入抢购活动明细id',
    },
    nextRushPurchaseDetailId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入上架后，下一场抢购活动明细id',
    },
    originalPrice: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入原价（购买价）',
    },
    newPrice: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入上架后新价格',
    },
    servicePrice: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入服务费（上架费）',
    },
    paymentOrderNo: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入第三方支付单号',
    },
    memberId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入上架会员id',
    },
    status: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入状态0默认1支付成功',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'orderSn',
      component: 'NInput',
      label: '订单号与抢购表一致',
      rules: [{ required: false }],
    },
    {
      field: 'rushPurchaseId',
      component: 'NInput',
      label: '活动场次id',
      rules: [{ required: false }],
    },
    {
      field: 'rushPurchaseDetailId',
      component: 'NInput',
      label: '抢购活动明细id',
      rules: [{ required: false }],
    },
    {
      field: 'nextRushPurchaseDetailId',
      component: 'NInput',
      label: '上架后，下一场抢购活动明细id',
      rules: [{ required: false }],
    },
    {
      field: 'originalPrice',
      component: 'NInput',
      label: '原价（购买价）',
      rules: [{ required: false }],
    },
    {
      field: 'newPrice',
      component: 'NInput',
      label: '上架后新价格',
      rules: [{ required: false }],
    },
    {
      field: 'servicePrice',
      component: 'NInput',
      label: '服务费（上架费）',
      rules: [{ required: false }],
    },
    {
      field: 'paymentOrderNo',
      component: 'NInput',
      label: '第三方支付单号',
      rules: [{ required: false }],
    },
    {
      field: 'memberId',
      component: 'NInput',
      label: '上架会员id',
      rules: [{ required: false }],
    },
    {
      field: 'status',
      component: 'NInput',
      label: '状态0默认1支付成功',
      rules: [{ required: false }],
    },
  ];

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedPutSaleOrderId = ref(); //当前编辑id
  const isEdit = ref(false); // 弹出框是否为编辑
  const editTitle = ref('');
  const dialog = useDialog();
  const formParams = reactive({
    id: null,
    orderSn: '',
    rushPurchaseId: '',
    rushPurchaseDetailId: '',
    nextRushPurchaseDetailId: '',
    originalPrice: '',
    newPrice: '',
    servicePrice: '',
    paymentOrderNo: '',
    memberId: '',
    status: '',
  });
  const formParamsBak = { ...formParams };

  const params = ref({});

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas,
  });

  function addTable() {
    // 新增清空表单
    Object.assign(formParams, formParamsBak);
    isEdit.value = false;
    showModal.value = true;
    editTitle.value = '新建';
  }

  const loadDataTable = async (res) => {
    return await getPutSaleOrderPage({ ...params.value, ...res });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let response;
        // 如果是编辑
        if (isEdit.value) {
          formParams.id = checkedPutSaleOrderId.value;
          response = await updatePutSaleOrder(formParams);
        } else {
          response = await savePutSaleOrder(formParams);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    checkedPutSaleOrderId.value = record.id;
    Object.assign(formParams, record);
    editTitle.value = '编辑';
    showModal.value = true;
    isEdit.value = true;
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deletePutSaleOrder(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    params.value = values;
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
</script>

<style lang="less" scoped></style>
